<html>
<head>
    <meta charset="UTF-8">
    <title>Web sockets test</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        var wsServer = 'ws://192.168.1.103:9502'; //服务器地址
        var websocket = new WebSocket(wsServer); //创建WebSocket对象
        websocket.onopen = function (evt) {
//已经建立连接

            $('#send').on('click',function(){
                var msg = $('#msg').val();
                if(msg == '')
                {
                    alert('不能发送空消息');
                    return ;
                }
                var arr =Array();
                arr[0]=1;   //发给谁
                arr[1]=msg;  //内容
                var str = JSON.stringify(arr);
                websocket.send(str);
            });
            $('#send_group').on('click',function(){
                var msg = $('#msg').val();
                if(msg == '')
                {
                    alert('不能发送空消息');
                    return ;
                }
                var arr =Array();
                arr[0]='all';   //发给谁
                arr[1]=msg;  //内容
                var str = JSON.stringify(arr);
                websocket.send(str);
            });
        };

        websocket.onclose = function (evt) {
//已经关闭连接
        };
        websocket.onmessage = function (evt) {
//收到服务器消息，使用evt.data提取\
            console.log(evt.data)
        };
        websocket.onerror = function (evt) {
//产生异常
        };

        function send(){
            $msg = $('#msg').val();
            websocket.send($msg);
        }

    </script>
</head>
<body>
<input id="msg" type="text" name="msg">
<input id="send" type="button" name="" value="单发">
<input id="send_group" type="button" name="" value="群发">
</body>
</html>
